package com.weixing.mall.provider.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AgentAuth;
import com.weixing.mall.core.support.auth.AgentInfo;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.provider.api.model.vo.AgentRpcVo;
import com.weixing.mall.provider.manager.AgentManager;
import com.weixing.mall.provider.model.dto.AgentPlaceOrderDto;
import com.weixing.mall.provider.model.dto.OrderAuditDto;
import com.weixing.mall.provider.model.enums.*;
import com.weixing.mall.provider.model.query.*;
import com.weixing.mall.provider.model.vo.*;
import com.weixing.mall.provider.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代理后台订单相关接口
 *
 * @author  siashan
 * @since  v1.0
 */
@RestController
@RequestMapping("order/agent")
public class AgentOrderController extends BaseController {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderTradeService orderTradeService;
    @Autowired
    private IOrderOperationService orderOperationService;
    @Autowired
    private AgentManager agentManager;
    @Autowired
    private IAgentOrderService agentOrderService;
    @Autowired
    private IKefuOrderService kefuOrderService;

    /**
     * 代理商下单
     *
     * @param dto 下单参数
     * @return 下单结果
     */
    @PostMapping("place")
    public Result place( @RequestBody AgentPlaceOrderDto dto) {
        AgentAuth auth = AuthUtil.getAgentExt();
        Result result1 = agentManager.checkAgent(auth.getAid(), dto.getAgentId());
        if (!result1.isSuccess()) {
            return result1;
        }
        AgentRpcVo data = (AgentRpcVo) result1.getData();
        Result result = orderTradeService.preOrderOfAgent(dto, data);
        return result;
    }

    /**
     * 订单详情
     *
     * @param id 订单id
     * @return 订单详情
     */
    @GetMapping("/getOrderDetails/{id}")
    public Result<OrderDetilVo> getOrderDetails(@PathVariable long id) {
        OrderDetilVo orderDetilVo = orderService.selectOrderDetails(id);
        Long aid = AuthUtil.getAgentExt().getAid();
        if (aid.longValue() != orderDetilVo.getAgentId()){
            orderDetilVo.setContactPhone(CommonUtil.coverMobile(orderDetilVo.getContactPhone()));
        }

        return ResultUtil.success(orderDetilVo);
    }


    /**
     * 订单查看
     *
     * @apiNote 订单列表,正价订单列表，秒杀活动订单列表，代理商活动订单列表
     *       订单查看  orderType 不传
     *      正价订单  orderType 传 1
     *      代理商活动订单  orderType 传 2
     *      秒杀活动订单  orderType 传 3
     *
     * @param query     订单查询参数
     * @since v1.0
     * @return 订单列表
     */
    @GetMapping("list")
    public Result<IPage<KefuAuditOrderVo>> orderList(CustomerOrderQuery query) {
        Long aid = AuthUtil.getAgentExt().getAid();
        IPage<KefuAuditOrderVo> page = kefuOrderService.selectOrderList(query, initMpPage());
        List<KefuAuditOrderVo> records = page.getRecords();
        if (CollUtil.isNotEmpty(records)){
            for (KefuAuditOrderVo vo : records){
                if (aid.longValue() != vo.getAgentId().longValue()){
                    vo.setContactPhone(CommonUtil.coverMobile(vo.getContactPhone()));
                }
            }
        }
        return ResultUtil.success(page);
    }




    /**
     * 代理商审核历史列表
     *
     * @param query     查询条件
     * @since v1.0
     * @return 审核历史
     */
    @GetMapping("auditHis")
    public Result<IPage<KefuAuditOrderVo>> auditHis(AgentAuditHisQuery query) {
        Long aid = AuthUtil.getAgentExt().getAid();
        IPage<KefuAuditOrderVo> page = agentOrderService.selectAuditHisList(aid,query, initMpPage());
        return ResultUtil.success(page);
    }

    /**
     * 代理商审核历史统计
     *
     * @param query 查询条件
     * @since v1.0
     * @return 统计信息
     */
    @GetMapping("auditHis/statistics")
    public Result<AuditHisCntVo> auditHisstatistics(AgentAuditHisQuery query) {
        query.setAgentId(AuthUtil.getAgentExt().getAid());
        AuditHisCntVo auditHisCntVo = agentOrderService.auditHisListSta(query);
        return ResultUtil.success(auditHisCntVo);
    }

    /**
     * 查看订单详情
     *
     * @param id    订单id
     * @return 订单详情
     */
    @GetMapping("orderDetail/{id}")
    public Result orderDetail(@PathVariable Long id) {
        Long agentId = AuthUtil.getAgentExt().getAid();
        FrontAgentOrderDetilsVo vo = agentOrderService.selectFrontAgentOrderDetils(id,agentId);
        return ResultUtil.success(vo);
    }


    /**
     * 查询代理商下单列表--运营管理后台专用
     *
     * @apiNote 不知道该接口是否有用
     *
     * @param query 查询条件
     * @return 结果
     */
    @PostMapping("")
    @Deprecated
    public Result<IPage<KefuAuditOrderVo>> list(@RequestBody AgentPlaceOrderQuery query) {
        query.setIsMaster(WhetherEnum.NO);
        query.setOrderFrom(OrderFromEnum.AGENT);
        return ResultUtil.success(agentOrderService.selectAgentPlaceOrderList(initMpPage(), query));
    }



    @ApiOperation(value = "查询代理商认领订单列表")
    @GetMapping("selectAgentClaimList")
    public Result selectAgentClaimList(AgentClaimQuery agentClaimQuery) {
        return ResultUtil.success(orderService.selectAgentClaimList(agentClaimQuery, initMpPage()));
    }


    /**
     * 待审核订单
     *
     * @apiNote 查询条件不能够传递agentId字段，应该传递auditor字段
     * @param query 查询条件
     * @return 待审核订单列表
     */
    @GetMapping("toAudit")
    public Result<IPage<FrontAgentOrderVo>> toAuditlist(AgentOrderQuery query) {
        Long aid = AuthUtil.getAgentExt().getAid();
        query.setAuditor(null == query.getAgentId() ? aid : query.getAgentId());
        query.setAgentId(null);
        query.setIsPay(WhetherEnum.YES);
        query.setAuditDept(AuditDeptEnum.AGENT);
        List<Integer> states = Lists.newArrayList();
        states.add(OrderStateEnum.HAS_PAY.getValue());
        states.add(OrderStateEnum.AUDITING.getValue());
        query.setOrderStates(states);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, aid);
        List<FrontAgentOrderVo> records = record.getRecords();
        if (CollUtil.isNotEmpty(records)){
            for (FrontAgentOrderVo vo : records){
                if (aid.longValue() != vo.getAgentId().longValue()){
                    vo.setContactPhone(CommonUtil.coverMobile(vo.getContactPhone()));
                }
            }
        }
        return ResultUtil.success(record);
    }

    /**
     * 已审核订单
     *
     * @apiNote 我审核过的单子,查询条件传递 hasAuditAgentId字段
     *
     * @param query  查询条件
     *
     * @return 已审核订单列表
     */
    @GetMapping("hasAudit")
    public Result hasAuditList(AgentOrderQuery query) {
        query.setAuditStatus(OrderAuditStateEnum.KEFU_AUDITING);
        Long aid = AuthUtil.getAgentExt().getAid();
        query.setIsPay(WhetherEnum.YES);
        query.setHasAuditAgentId(null == query.getAgentId() ? aid : query.getAgentId());
        query.setAgentId(null);
        Map<String,Object> returnMap = new HashMap<>();
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, aid);
        List<FrontAgentOrderVo> records = record.getRecords();
        if (CollUtil.isNotEmpty(records)){
            for (FrontAgentOrderVo vo : records){
                if (aid.longValue() != vo.getAgentId().longValue()){
                    vo.setContactPhone(CommonUtil.coverMobile(vo.getContactPhone()));
                }
            }
        }
        Map<String,Object> totalAmount = agentOrderService.selectAgentOrderListPriceTotal(query, aid);
        returnMap.put("data",record);
        returnMap.put("totalAmount", ObjectUtil.isNotEmpty(totalAmount.get("totalAmount"))?totalAmount.get("totalAmount"):0);
        return ResultUtil.success(returnMap);
    }


    /**
     * 订单审核
     *
     * @param orderAudit  审核参数
     * @return 审核结果
     */
    @PostMapping("audit")
    public Result frontAgentAudit( @RequestBody OrderAuditDto orderAudit) {
        AgentAuth auth = AuthUtil.getAgentExt();
        orderOperationService.agentAudit(orderAudit, auth.getAid(),auth.getAName());
        return ResultUtil.success();
    }


    /**
     * 订单批量审核
     * @param ids 订单id，多个英文逗号隔开
     * @return 审核结果
     */
    @PostMapping("batchAudit/{ids}")
    public Result batchAudit( @PathVariable String ids) {
        AgentAuth auth = AuthUtil.getAgentExt();
        String[] arrayList = ids.split(",");
        List<OrderAuditDto> orderAuditDtoList = Lists.newArrayList();
        if (arrayList != null && arrayList.length > 0) {
            OrderAuditDto dto = null;
            for (String ss : arrayList) {
                dto = new OrderAuditDto();
                dto.setAuditState(AuditStateEnum.AGGREE);
                dto.setOrderId(Long.valueOf(ss));
                orderAuditDtoList.add(dto);
            }
        }
        if (CollUtil.isNotEmpty(orderAuditDtoList)) {
            for (OrderAuditDto dto : orderAuditDtoList) {
                orderOperationService.agentAudit(dto, auth.getAid(),auth.getAName());
            }
        }
        return ResultUtil.success();
    }

    /**
     * 判断是否有未审核订单
     * @param agentId 代理id
     * @return 是否
     */
    @GetMapping("/checkHasAuditOrder")
    public Result checkHasAuditOrder(long agentId) {
        AgentOrderQuery query = new AgentOrderQuery();
        query.setIsPay(WhetherEnum.YES);
        query.setAuditDept(AuditDeptEnum.AGENT);
        List<Integer> states = Lists.newArrayList();
        states.add(OrderStateEnum.HAS_PAY.getValue());
        states.add(OrderStateEnum.AUDITING.getValue());
        query.setOrderStates(states);
        query.setAgentIdForQueryAll(agentId);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(new Page(1, 10), query, agentId);
        if (CollUtil.isNotEmpty(record.getRecords())){
            return ResultUtil.success(WhetherEnum.YES.getValue());
        }
        return ResultUtil.success(WhetherEnum.NO.getValue());
    }
}
